<?php
namespace Admin\Controller;
use Vendor\Tree;
use Think\Model;
use Think\Exception;

class VipcardController extends ComController
{
    public function index()
    {
        $p      = I('get.p', 1, 'intval');
        $type   = I('get.type',1,'intval');
        $search = I('keyword') ? I('keyword') : '';

        if (!empty($search)) {
            $map['card_name'] = array('like', "%$search%");
            $this->assign('search', $search);
        }

        $type = I('cardtype',0,'intval');
        $status = I('status','');

        if (!empty($type)) {
            $map['type'] = $type;
            $this->assign('type', $type);
        }

        if (!empty($status)) {
            $map['status'] = $status;
        }

        $this->assign('status', $status);

        $psize = 20;

        $m    = M('vip_card c');
        $list = $m->join("__CARD_TYPE__ t ON c.type=t.type_id")
        ->field("c.*,t.type_name typename")
        ->where($map)
        ->order('id DESC')->page($p, $psize)->select();

        $count = $m->join("__CARD_TYPE__ t ON c.type=t.type_id")
        ->where($map)->count();

        $page = new \Think\Page($count, $psize);
        $page = $page->show();

        $this->getCardTypeList($type);

        $this->assign('page', $page);
        $this->assign('list', $list);

        return $this->display();
    }

    public function setting(){
        $p      = I('get.p', 1, 'intval');
        $type   = I('get.type',1,'intval');
        $search = I('keyword') ? I('keyword') : '';
        $map = array(
            'status' => 1
        );

        if (!empty($search)) {
            $map['cardno'] = array('like', "%$search%");
            $this->assign('search', $search);
        }

        $type = I('cardtype',0,'intval');

        if (!empty($type)) {
            $map['c.type_id'] = $type;
            $this->assign('type', $type);
        }

        $psize = 20;

        $m    = M('card_list c');
        $list = $m->join("__CARD_TYPE__ t ON c.type_id=t.type_id")
        ->field("c.*,t.type_name typename")
        ->where($map)
        ->order('card_id DESC')->page($p, $psize)->select();

        $count = $m->join("__CARD_TYPE__ t ON c.type_id=t.type_id")
        ->where($map)->count();

        $page = new \Think\Page($count, $psize);
        $page = $page->show();

        $this->getCardTypeList($type);

        $this->assign('page', $page);
        $this->assign('list', $list);

        return $this->display();
    }

    public function add(){
        if (!IS_POST) {
            $this->getCardTypeList();
            return $this->display();
        }
        $data = I('post.');

        if (!isset($data['cardtypeid']) || empty($data['cardtypeid'])) {
            return $this->error('请选择卡券类型');
        }

        $model = new Model();
        $num = intval($data['cardnum']);

        try{
            $model->startTrans();
            //添加基本的信息
            $cardInfo = array(
                'card_name'     => trim($data['cardname']),
                'type_id'       => intval($data['cardtypeid']),
                'card_img'      => trim($data['cardPic']),
                'start_time'    => trim($data['starttime']),
                'end_time'      => trim($data['endtime']),
                'card_address'  => trim($data['conversionAddr']),
                'card_integral' => intval($data['score']),
                'card_money'    => intval($data['money']),
                'card_nums'     => $num,
                'create_time'   => getModeltime(),
                'use_money' => $data['usemoney']
            );

            $cardId = $model->table('__CARD_LIST__')->data($cardInfo)->add();

            if (empty($cardId)) {
                throw new Exception("添加基本信息错误", -1);
            }

            $vipCardInfo = array(
                'cardId' => $cardId,
                'ctime' => time(),
                'type' => $data['cardtypeid'],
                'usemoney' => $data['usemoney'],
                'money' => $data['money']
            );

            if (!empty($data['starttime']) && !empty($data['endtime'])) {
                $vipCardInfo['stime'] = strtotime($data['starttime']);
                $vipCardInfo['etime'] = strtotime($data['endtime']);
            }else{
                throw new Exception('有效时间不能为空', -2);
            }

            $insertData = array();
            for ($i = 0; $i < $num; $i++) {
                $cardnopwd = $this->getCardNoPwd();
                $vipCardInfo['cardno'] = $cardnopwd['no'];
                $vipCardInfo['cardpwd'] = $cardnopwd['pwd'];
                $insertData[] = $vipCardInfo;
            }

            $res = $model->table('__VIP_CARD__')->addAll($insertData);

            if (!$res) {
                throw new Exception('添加失败', -1);
            }
            $model->commit();
            addlog('添加卡券');
            return $this->success('添加成功', 'index');
        }catch(Exception $e){
            $model->rollback();
            return $this->error($e->getMessage());
        }
    }

    public function edit(){
        $id = I('param.id',0, 'intval');
        if (empty($id)) {
            return $this->error('参数错误！');
        }

        if (!IS_POST) {
            $info = M('card_list')->where(['card_id'=>intval($id)])->find();

            if (empty($info)) {
                return $this->error('没有找到数据');
            }

            $this->assign('info', $info);

            return $this->display();
        }

        $data = I('post.');

        $saveInfo = array(
            'card_name'    => trim($data['cardname']),
            'card_img'     => trim($data['cardPic']),
            'card_address' => trim($data['conversionAddr']),
        );

        $res = M('card_list')->data($saveInfo)->where(['card_id'=>intval($id)])->save();

        if (false === $res) {
            return $this->error('修改失败');
        }

        return $this->success('修改成功','setting');
    }

    public function delVipCard(){
        $id = I('get.id',0,'intval');

        if (empty($id)) {
            return $this->error('参数错误');
        }

        $m = new Model();
        try{
            $m->startTrans();
            $res = $m->table('__CARD_LIST__')->where(['card_id'=>$id])->save(['status'=>-1]);

            if (false === $res) {
                throw new Exception('删除失败', -1);
            }

            // $res = $m->table('__VIP_CARD__')>where(['cardId'=>$id])->save(['status'=>-1])
            $m->commit();
        return $this->success('删除成功');
        }catch(Exception $e){
            $m->rollback();
            return $this->error($e->getMessage());
        }
    }

    public function del(){
        $aids = isset($_REQUEST['ids']) ? $_REQUEST['ids'] : false;

        if ($aids) {
            if (is_array($aids)) {
                $aids = implode(',', $aids);
                $map['id'] = array('in', $aids);
            } else {
                $map = 'id=' . $aids;
            }

            if (M('vip_card')->where($map)->delete()) {
                addlog('删除卡券，AID：' . $aids);
                $this->success('恭喜，删除成功！');
            } else {
                $this->error('参数错误！');
            }
        } else {
            $this->error('参数错误！');
        }
    }

    //卡券分类
    private function getCardTypeList($id=0){
        $typeList = M('card_type')->field('type_id id, type_name name')->select();

        $tree = new Tree($typeList);

        $str = "<option value=\$id \$selected>\$name</option>"; //生成的形式
        $typeList = $tree->get_tree(0, $str, $id);

        $this->assign('typeList', $typeList);
    }

    //生成卡券密码
    private function getCardNoPwd() {
        $dict_no = "0123456789";
        $length_no = 10;
        $dict_pwd = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        $length_pwd = 10;
        $card['no'] = "";
        $card['pwd'] = "";
        for ($i = 0; $i < $length_no; $i++) {
            $card['no'].=$dict_no[rand(0, (strlen($dict_no) - 1))];
        }
        for ($i = 0; $i < $length_pwd; $i++) {
            $card['pwd'].=$dict_pwd[rand(0, (strlen($dict_pwd) - 1))];
        }
        return $card;
    }

    public function uselist(){
        $p      = I('get.p', 1, 'intval');
        $type   = I('get.type',1,'intval');
        $search = I('keyword') ? I('keyword') : '';
        $map = array('c.status' => 2);

        if (!empty($search)) {
            $map['user_name'] = array('like', "%$search%");
            $this->assign('search', $search);
        }

        $type = I('cardtype',0,'intval');

        if (!empty($type)) {
            $map['type'] = $type;
            $this->assign('type', $type);
        }

        $psize = 20;

        $m    = M('vip_card c');
        $list = $m->join("__CARD_TYPE__ t ON c.type=t.type_id")
        ->join("__USERS__ u ON c.uid=u.user_id")
        ->field("c.*,t.type_name typename,u.user_name uname")
        ->where($map)
        ->order('id DESC')->page($p, $psize)->select();

        $count = $m->join("__CARD_TYPE__ t ON c.type=t.type_id")
        ->join("__USERS__ u ON u.user_id=c.uid")
        ->where($map)->count();

        $page = new \Think\Page($count, $psize);
        $page = $page->show();

        $this->getCardTypeList($type);

        $this->assign('page', $page);
        $this->assign('list', $list);

        return $this->display();
    }
}
